package pos;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatEditText;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;

import net.ck.hzq.R;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import Bean.PhoneNumerBean;
import Bean.PhoneNumerParamBean;
import Utils.HelloWordModel;
import Utils.ResourcesManager;
import Utils.SharedPrefStore;
import Utils.SystemDatas;
import Utils.ToastUtil;
import activity.glide.GlideApp;
import base.BaseActivity;
import base.BaseBiz;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import dao.AddPosInput;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ui.activity.profit.biz.ProfitBiz;
import ui.model.GetShareIamgeBean;

/**
 * by BF00233 on 2018/12/15.
 */
public class OldPosAuthByAutoMaticActivity extends BaseActivity implements View.OnClickListener {

    ProfitBiz profitBiz;
    private CountDownTimer timer;
    private String mCode="";


    private TextView tv_rate;
    private ImageView share_image;
    //初始页面，点击下一步后的页面
    LinearLayout detail_info_layout, nexttaplinear;
    TextView nexttapusername, nexttapuserphone, nexttapsnno, nexttaprate, automaticsharebtn;

    // 详细信息填写
    private EditText detailIdNo, detailIdName;
    private AppCompatEditText phoneEt, verifyCodeEt, snEt;
    private String shareUrl = "";

    // 验证码
    private TextView getVerifyCode, nexttap, zxing_sao;
    private ImageView sm_back;
    private String ratenum;//费率

    private Bitmap bitmap;//分享的图片对象

    public static void start(Context context) {
        Intent intent = new Intent(context, OldPosAuthByAutoMaticActivity.class);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_old_pos_authbyautomatic;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        profitBiz = new ProfitBiz();
        sm_back = findViewById(R.id.sm_back);//上面返回按钮
        nexttap = findViewById(R.id.nexttap);//下一步按钮
        share_image = findViewById(R.id.share_image);
        detailIdName = findViewById(R.id.detail_id_name);
        tv_rate = findViewById(R.id.tv_rate);
        phoneEt = findViewById(R.id.et_merchant_phone);
        verifyCodeEt = findViewById(R.id.et_verify_code);
        snEt = findViewById(R.id.et_sn);
        zxing_sao = findViewById(R.id.zxing_sao);
        detail_info_layout = findViewById(R.id.detail_info_layout);
        nexttaplinear = findViewById(R.id.nexttaplinearlayout);

        nexttapusername = findViewById(R.id.nexttapusername);
        nexttapuserphone = findViewById(R.id.nexttapuserphone);
        nexttapsnno = findViewById(R.id.nexttapsnno);
        nexttaprate = findViewById(R.id.nexttaprate);
        automaticsharebtn = findViewById(R.id.automaticsharebtn);

        // 验证码
        getVerifyCode = findViewById(R.id.get_verify_code);
        getVerifyCode.setOnClickListener(this);
        tv_rate.setOnClickListener(this);
        sm_back.setOnClickListener(this);
        nexttap.setOnClickListener(this);
        zxing_sao.setOnClickListener(this);
        automaticsharebtn.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != bitmap) {
            bitmap.recycle();
            bitmap = null;
        }
        if (null != timer) {
            timer.cancel();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.get_verify_code:
                requestVerifyCode();
                break;
            case R.id.sm_back:
                finish();
                break;
            case R.id.nexttap:
                submitData();
                break;
            case R.id.automaticsharebtn:
                onOneKeyShare();
                break;
            case R.id.tv_rate:
//                                profitBiz.GetUserRate2(new BaseBiz.Callback<List<String>>() {
//                    @Override
//                    public void onSuccess(List<String> info) {
//                        String[] items = new String[info.size()];
//                        for (int i = 0;i<info.size();i++){
//                            items[i]=info.get(i);
//                        }
//                        new QMUIDialog.CheckableDialogBuilder(OldPosAuthByAutoMaticActivity.this)
//                                .addItems(items, (dialogInterface, i) -> {
//                                    ratenum = items[i];
//                                    tv_rate.setText(ratenum);
//                                    tv_rate.setTextColor(getResources().getColor(R.color.tc_666666));
//                                    dialogInterface.dismiss();
//                                })
//                                .create()
//                                .show();
//
//                    }
//
//                    @Override
//                    public void onFailure(List<String> info) {
//
//                    }
//                });


//                profitBiz.GetUserRate(TobuyApplication.getCustomId(),new BaseBiz.Callback<RateLevelBean>() {
//                    @Override
//                    public void onSuccess(RateLevelBean info) {
//
//                        if(info.getLevelAmount()<=5){
//                            showLevelRate();
//                        }else{
//                            showLevelRate2();
//                        }
//
//                    }
//
//                    @Override
//                    public void onFailure(RateLevelBean info) {
//
//                    }
//                });
                break;

            case R.id.zxing_sao:
                IntentIntegrator integrator = new IntentIntegrator(OldPosAuthByAutoMaticActivity.this);
                // 设置要扫描的条码类型，ONE_D_CODE_TYPES：一维码，QR_CODE_TYPES-二维码
                integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
                integrator.setCaptureActivity(ScanActivity.class); //设置打开摄像头的Activity
                integrator.setPrompt("请扫描SN"); //底部的提示文字，设为""可以置空
                integrator.setCameraId(0); //前置或者后置摄像头
                integrator.setBeepEnabled(true); //扫描成功的「哔哔」声，默认开启
                integrator.setBarcodeImageEnabled(true);
                integrator.initiateScan();

                break;
        }
    }
    private void showLevelRate() {
        String[] items = new String[]{"0.60%","0.61%","0.62%","0.63%","0.64%","0.65%"};
        new QMUIDialog.CheckableDialogBuilder(this)
//                .setCheckedIndex(Arrays.binarySearch(items, mMerchantType))
                .addItems(items, (dialogInterface, i) -> {
                    ratenum = items[i];
                    tv_rate.setText(ratenum);
                    tv_rate.setTextColor(getResources().getColor(R.color.tc_666666));
                    dialogInterface.dismiss();
                })
                .create()
                .show();
    }
    private void showLevelRate2() {
        String[] items = new String[]{"0.55%","0.56%","0.57%","0.58%","0.59%","0.60%","0.61%","0.62%","0.63%","0.64%","0.65%"};
        new QMUIDialog.CheckableDialogBuilder(this)
//                .setCheckedIndex(Arrays.binarySearch(items, mMerchantType))
                .addItems(items, (dialogInterface, i) -> {
                    ratenum = items[i];
                    tv_rate.setText(ratenum);
                    tv_rate.setTextColor(getResources().getColor(R.color.tc_666666));
                    dialogInterface.dismiss();
                })
                .create()
                .show();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (scanResult != null) {
            String result = scanResult.getContents();
            snEt.setText(result);
        }

    }

    private void submitData() {
        if (!checkDetailInput()) {
            return;
        }
        showProgressDialog();
        nexttap.setClickable(false);
        SharedPrefStore store = new SharedPrefStore();
        AddPosInput param = new AddPosInput();
        param.customId = store.getString("id", "0");
        param.merchantName = detailIdName.getText().toString();
        param.rate = tv_rate.getText().toString().replace("%", "");
        param.phone = phoneEt.getEditableText().toString();
        param.sn = snEt.getEditableText().toString().trim().replace("\n", "");

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(param));
        profitBiz.AddSimplePOS(requestBody, new BaseBiz.Callback<Object>() {
            @Override
            public void onSuccess(Object info) {

                detail_info_layout.setVisibility(View.GONE);
                nexttaplinear.setVisibility(View.VISIBLE);
                nexttapusername.setText(detailIdName.getText().toString());
                nexttapuserphone.setText(phoneEt.getEditableText().toString());
                nexttapsnno.setText(snEt.getEditableText().toString());
                nexttaprate.setText(tv_rate.getText().toString());
                profitBiz.GetShareImage(requestBody, new BaseBiz.Callback<GetShareIamgeBean>() {
                    @Override
                    public void onSuccess(GetShareIamgeBean info) {
                        dismissProgressDialog();
                        returnBitMap(info.getItems().getOrganizationQrCode());
                        shareUrl = info.getItems().getOrganizationUrl();
                        GlideApp.with(OldPosAuthByAutoMaticActivity.this)
                                .load(info.getItems().getOrganizationQrCode())
                                .error(R.drawable.about)
                                .placeholder(R.drawable.about)
                                .into(share_image);

                    }

                    @Override
                    public void onFailure(GetShareIamgeBean info) {
                        nexttap.setClickable(true);
                        dismissProgressDialog();
                    }
                });
            }

            @Override
            public void onFailure(Object info) {
                nexttap.setClickable(true);
                dismissProgressDialog();
            }
        });
    }

    public void returnBitMap(final String url) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                URL imageurl = null;
                try {
                    imageurl = new URL(url);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    //这是一个一步请求，不能直接返回获取，要不然永远为null
                    //在这里得到BitMap之后记得使用Hanlder或者EventBus传回主线程，不过现在加载图片都是用框架了，很少有转化为Bitmap的需求
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void requestVerifyCode() {
        if (TextUtils.isEmpty(phoneEt.getText()) || TextUtils.isEmpty(phoneEt.getText().toString().trim())) {
            ToastUtil.showNormal(this, "请输入手机号码");
            return;
        }
        if (timer != null) {
            timer.cancel();
        }
        getVerifyCode.setEnabled(false);
        timer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long l) {
                getVerifyCode.setText(l / 1000 + "秒后重发");
            }

            @Override
            public void onFinish() {
                getVerifyCode.setEnabled(true);
                getVerifyCode.setText("获取验证码");
            }
        };
        timer.start();

        String phone = phoneEt.getText().toString().trim();
        PhoneNumerParamBean p = new PhoneNumerParamBean();
        p.setTelephoneNumber(phone);
        Call<PhoneNumerBean> userMsgCall2 = HelloWordModel.getInstance(this).getphonecode(SystemDatas.GetService_URL
                ("getphonecode2"), p);
        userMsgCall2.enqueue(new Callback<PhoneNumerBean>() {
            @Override
            public void onResponse(Call<PhoneNumerBean> call, final Response<PhoneNumerBean> response) {
                try {
                    if (response.body() != null && response.body().getMsg().equals("success")) {
                        ToastUtil.showNormal(OldPosAuthByAutoMaticActivity.this, "获取成功!");
                        mCode = response.body().getData().getCode();
                    } else {
                        ToastUtil.showNormal(OldPosAuthByAutoMaticActivity.this, response.body().getMsg());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<PhoneNumerBean> call, Throwable t) {
                ToastUtil.showNormal(OldPosAuthByAutoMaticActivity.this, "获取失败");
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private boolean checkDetailInput() {
        if (TextUtils.isEmpty(verifyCodeEt.getEditableText().toString()) ||TextUtils.isEmpty(phoneEt.getEditableText().toString())||TextUtils.isEmpty(snEt.getEditableText().toString())||TextUtils.isEmpty(detailIdName.getText().toString())) {
            showFailureTipDialog("请输入所有必要信息");
            return false;
        }
        if (!TextUtils.equals(mCode, verifyCodeEt.getEditableText().toString())) {
            showFailureTipDialog("验证码错误");
            return false;
        }

        return true;
    }


    /**
     * 一键分享
     */
    private void onOneKeyShare() {

        //TODO
//        ResourcesManager.getInstace(MobSDK.getContext());
        cn.sharesdk.onekeyshare.OnekeyShare oks = new cn.sharesdk.onekeyshare.OnekeyShare();
        oks.setAddress("http://www.tobuy.net/");
        ResourcesManager manager = ResourcesManager.getInstace(OldPosAuthByAutoMaticActivity.this);
        oks.setTitle(detailIdName.getText().toString() + "邀请你开通商户");//标题
        oks.setText("自助报单，方便快捷");//内容
        oks.setUrl(shareUrl);//链接
        oks.setTitleUrl(shareUrl);
        oks.setImageData(bitmap);
        oks.setCallback(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                ToastUtil.show(OldPosAuthByAutoMaticActivity.this, "发送成功");
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                ToastUtil.show(OldPosAuthByAutoMaticActivity.this, "发送失败");
            }

            @Override
            public void onCancel(Platform platform, int i) {
                ToastUtil.show(OldPosAuthByAutoMaticActivity.this, "取消发送");
            }
        });
        oks.show(OldPosAuthByAutoMaticActivity.this);
    }
}
